

public class jishengjun {

    public static void main(String[] args) {
        Node node1 = new Node(9);
        Node node2 = new Node(5);
        Node node3 = new Node(3);
        Node node4 = new Node(4);
        Node node5 = new Node(7);
        Node node6 = new Node(8);
        Node node7 = new Node(2);
        Node node8 = new Node(1);
        Node node9 = new Node(6);

        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = node6;
        node6.next = node7;
        node7.next = node8;
        node8.next = node9;

        Node sortedNode = sortList(node1,node9);
        while (sortedNode.next != null) {
            System.out.println(sortedNode.val);
            sortedNode = sortedNode.next;
        }
    }


    public static Node sortList(Node head, Node end) {
        if (head == end) {
            return head;
        }
        Node minNode = head;
        Node maxNode = head;
        Node currentNode = head.next;
        while (currentNode != end) {
            if (currentNode.val < head.val) {
                maxNode.next = currentNode.next;
                currentNode.next = minNode;
                minNode = currentNode;
                currentNode = maxNode.next;
            } else {
                maxNode = currentNode;
                currentNode = currentNode.next;
            }
        }
        Node result = sortList(minNode, head);
        sortList(head, maxNode);
        return result;
    }

    public static class Node {
        int val;
        Node next;

        Node(int x) {
            val = x;
        }
    }
}
